from PyQt6.QtWidgets import (
    QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit, QPushButton,
    QTextEdit, QListWidget, QListWidgetItem, QFrame, QGroupBox,
    QScrollArea, QGridLayout, QSpinBox, QCheckBox, QComboBox,
    QTabWidget, QTableWidget, QTableWidgetItem, QHeaderView
)
from PyQt6.QtCore import Qt, pyqtSignal, QPropertyAnimation, QEasingCurve, QRect
from communication import ToggleSwitch
import json
import os
from config_manager import config_manager

class ChatWidget(QWidget):
    def __init__(self):
        super().__init__()
        
        # 存储所有UI字段的引用
        self.ui_fields = {}
        # 配置文件名
        self.config_filename = "chat_config.json"
        
        # 迁移旧配置文件
        old_config_path = "chat_config.json"
        config_manager.migrate_old_config(old_config_path, self.config_filename)
        
        # 默认配置数据
        self.default_config = {
            "tableName": "fl",
            "settings": {
                "response": True,
                "ai": True,
                "ag": 5
            },
            "item1": {
                "toggle": True,
                "startHour": "09",
                "startMinute": "00",
                "endHour": "18",
                "endMinute": "00",
                "filterToday": True,
                "readMessage1": "社区全职高薪公司新设立的业务部门，主",
                "readMessage2": "我们准备资源提供帮助吸收优秀的人才3-6K不",
                "readMessage3": "1.上班时间早九晚六，周末双休不加班",
                "unreadMessage1": "社区全职高薪公司新设立的业务部门，主",
                "unreadMessage2": "我们准备资源提供帮助吸收优秀的人才3-6K不",
                "unreadMessage3": "1.上班时间早九晚六，周末双休不加班"
            },
            "item2": {
                "toggle": False,
                "startHour": "14",
                "startMinute": "00",
                "endHour": "16",
                "endMinute": "00",
                "filterToday": False,
                "readMessage1": "",
                "readMessage2": "",
                "readMessage3": "",
                "unreadMessage1": "",
                "unreadMessage2": "",
                "unreadMessage3": ""
            },
            "item3": {
                "toggle": False,
                "startHour": "20",
                "startMinute": "00",
                "endHour": "22",
                "endMinute": "00",
                "filterToday": False,
                "readMessage1": "",
                "readMessage2": "",
                "readMessage3": "",
                "unreadMessage1": "",
                "unreadMessage2": "",
                "unreadMessage3": ""
            }
        }
        self.init_ui()
        self.load_config()
    
    def load_config(self):
        """从AppData加载配置数据到UI字段"""
        try:
            self.config_data = config_manager.load_config(self.config_filename, self.default_config)
            
            # 加载复聊设置
            if 'settings' in self.config_data:
                settings = self.config_data['settings']
                if 'new_msg_switch' in self.ui_fields:
                    self.ui_fields['new_msg_switch'].setChecked(settings.get('response', True))
                if 'smart_switch' in self.ui_fields:
                    self.ui_fields['smart_switch'].setChecked(settings.get('ai', True))
                if 'limit_input' in self.ui_fields:
                    self.ui_fields['limit_input'].setText(str(settings.get('ag', 5)))
            
            # 加载三个时间段的配置
            for i in range(1, 4):
                item_key = f'item{i}'
                if item_key in self.config_data:
                    item_data = self.config_data[item_key]
                    
                    # 时间段开关
                    switch_key = f'time_switch_{i}'
                    if switch_key in self.ui_fields:
                        self.ui_fields[switch_key].setChecked(item_data.get('toggle', False))
                    
                    # 时间设置
                    hour_start_key = f'hour_start_{i}'
                    minute_start_key = f'minute_start_{i}'
                    hour_end_key = f'hour_end_{i}'
                    minute_end_key = f'minute_end_{i}'
                    
                    if hour_start_key in self.ui_fields:
                        self.ui_fields[hour_start_key].setCurrentText(item_data.get('startHour', '09'))
                    if minute_start_key in self.ui_fields:
                        self.ui_fields[minute_start_key].setCurrentText(item_data.get('startMinute', '00'))
                    if hour_end_key in self.ui_fields:
                        self.ui_fields[hour_end_key].setCurrentText(item_data.get('endHour', '18'))
                    if minute_end_key in self.ui_fields:
                        self.ui_fields[minute_end_key].setCurrentText(item_data.get('endMinute', '00'))
                    
                    # 过滤今日已聊开关
                    filter_key = f'filter_switch_{i}'
                    if filter_key in self.ui_fields:
                        self.ui_fields[filter_key].setChecked(item_data.get('filterToday', False))
                    
                    # 消息文本框
                    for j in range(1, 4):
                        read_key = f'read_message_{i}_{j}'
                        unread_key = f'unread_message_{i}_{j}'
                        
                        if read_key in self.ui_fields:
                            self.ui_fields[read_key].setText(item_data.get(f'readMessage{j}', ''))
                        if unread_key in self.ui_fields:
                            self.ui_fields[unread_key].setText(item_data.get(f'unreadMessage{j}', ''))
            
            print("复聊配置加载成功")
            
        except Exception as e:
            print(f"加载配置失败: {e}")
    
    def save_config(self):
        """保存UI字段数据到AppData的JSON文件"""
        try:
            # 更新复聊设置
            self.config_data['settings'] = {
                'response': self.ui_fields.get('new_msg_switch', {}).isChecked() if 'new_msg_switch' in self.ui_fields else True,
                'ai': self.ui_fields.get('smart_switch', {}).isChecked() if 'smart_switch' in self.ui_fields else True,
                'ag': int(self.ui_fields.get('limit_input', {}).text() or '5') if 'limit_input' in self.ui_fields else 5
            }
            
            # 更新三个时间段的配置
            for i in range(1, 4):
                item_key = f'item{i}'
                
                # 获取UI字段值
                toggle = self.ui_fields.get(f'time_switch_{i}', {}).isChecked() if f'time_switch_{i}' in self.ui_fields else False
                start_hour = self.ui_fields.get(f'hour_start_{i}', {}).currentText() if f'hour_start_{i}' in self.ui_fields else '09'
                start_minute = self.ui_fields.get(f'minute_start_{i}', {}).currentText() if f'minute_start_{i}' in self.ui_fields else '00'
                end_hour = self.ui_fields.get(f'hour_end_{i}', {}).currentText() if f'hour_end_{i}' in self.ui_fields else '18'
                end_minute = self.ui_fields.get(f'minute_end_{i}', {}).currentText() if f'minute_end_{i}' in self.ui_fields else '00'
                filter_today = self.ui_fields.get(f'filter_switch_{i}', {}).isChecked() if f'filter_switch_{i}' in self.ui_fields else False
                
                # 获取消息文本
                messages = {}
                for j in range(1, 4):
                    read_key = f'read_message_{i}_{j}'
                    unread_key = f'unread_message_{i}_{j}'
                    
                    messages[f'readMessage{j}'] = self.ui_fields.get(read_key, {}).text() if read_key in self.ui_fields else ''
                    messages[f'unreadMessage{j}'] = self.ui_fields.get(unread_key, {}).text() if unread_key in self.ui_fields else ''
                
                # 更新配置数据
                self.config_data[item_key] = {
                    'toggle': toggle,
                    'startHour': start_hour,
                    'startMinute': start_minute,
                    'endHour': end_hour,
                    'endMinute': end_minute,
                    'filterToday': filter_today,
                    **messages
                }
            
            # 保存到AppData
            config_manager.save_config(self.config_filename, self.config_data)
            print(f"配置已保存到: {config_manager.get_config_path(self.config_filename)}")
            
        except Exception as e:
            print(f"保存配置失败: {e}")
            return None
    
    def init_ui(self):
        """初始化复聊配置界面"""
        self.setStyleSheet("""
            QWidget {
                background-color: white;
                color: black;
                font-family: 'Microsoft YaHei', Arial, sans-serif;
            }
            QLabel {
                font-size: 11px;
                font-weight: bold;
                border: none;
                color: black;
            }
        """)
        
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(15, 15, 15, 15)
        main_layout.setSpacing(10)
        
        # 标题和保存按钮
        header_layout = QHBoxLayout()
        
        title_label = QLabel("🔄 复聊配置管理")
        title_label.setStyleSheet("""
            QLabel {
                font-size: 20px;
                font-weight: bold;
                color: black;
                background-color: white;
                border: none;
            }
        """)
        header_layout.addWidget(title_label)
        
        header_layout.addStretch()
        
        # 保存按钮
        save_btn = QPushButton("💾 保存配置")
        save_btn.setStyleSheet("""
            QPushButton {
                background-color: #007bff;
                color: white;
                border: none;
                padding: 8px 20px;
                border-radius: 4px;
                font-weight: bold;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: #0056b3;
            }
            QPushButton:pressed {
                background-color: #004085;
            }
        """)
        save_btn.clicked.connect(self.save_config)
        header_layout.addWidget(save_btn)
        
        main_layout.addLayout(header_layout)
        
        # 主要内容区域
        content_layout = QVBoxLayout()
        content_layout.setSpacing(15)
        
        # 创建复聊设置分组
        self.create_chat_settings(content_layout)
        
        # 创建时间段设置分组
        self.create_time_settings(content_layout)
        
        main_layout.addLayout(content_layout)
    
    def create_chat_settings(self, parent_layout):
        """创建复聊设置分组"""
        group = QGroupBox("⚙️ 复聊设置")
        group.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                color: black;
                border: 1px solid #ccc;
                border-radius: 6px;
                margin-top: 8px;
                padding-top: 8px;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 5px 0 5px;
                color: black;
            }
        """)
        layout = QVBoxLayout(group)
        layout.setSpacing(8)
        
        # 第一行：复新消息、智能调整、复聊上限
        first_row = QHBoxLayout()
        first_row.setSpacing(20)
        
        # 复新消息开关
        new_msg_switch = ToggleSwitch("", True)
        self.ui_fields['new_msg_switch'] = new_msg_switch
        first_row.addWidget(QLabel("复新消息"))
        first_row.addWidget(new_msg_switch)
        
        first_row.addStretch()
        
        # 智能调整开关
        smart_switch = ToggleSwitch("", True)
        self.ui_fields['smart_switch'] = smart_switch
        first_row.addWidget(QLabel("智能调整"))
        first_row.addWidget(smart_switch)
        
        first_row.addStretch()
        
        # 复聊上限
        first_row.addWidget(QLabel("复聊上限"))
        limit_input = QLineEdit("5")
        limit_input.setFixedWidth(60)
        limit_input.setStyleSheet("""
            QLineEdit {
                background-color: white;
                color: black;
                border: 1px solid #ccc;
                padding: 4px;
                border-radius: 3px;
            }
        """)
        self.ui_fields['limit_input'] = limit_input
        first_row.addWidget(limit_input)
        first_row.addStretch()
        layout.addLayout(first_row)
        parent_layout.addWidget(group)
    
    def create_time_settings(self, parent_layout):
        """创建时间段设置分组"""
        group = QGroupBox("⏰ 时间段设置")
        group.setStyleSheet("""
            QGroupBox {
                font-weight: bold;
                color: black;
                border: 1px solid #ccc;
                border-radius: 6px;
                margin-top: 8px;
                padding-top: 8px;
                background-color: white;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 5px;
                color: black;
            }
        """)
        layout = QVBoxLayout(group)
        layout.setSpacing(15)
        layout.setContentsMargins(10, 15, 10, 10)
        
        # 创建三个时间段，每个时间段包含时间控制和文本框
        for i in range(3):
            time_index = i + 1
            # 时间控制行
            time_row = self.create_time_row(i == 0, time_index)  # 第一行默认开启
            layout.addLayout(time_row)
            
            # 文本框行
            text_rows = self.create_message_text_rows(time_index)
            layout.addLayout(text_rows)
            
            # 添加分隔线（除了最后一个）
            if i < 2:
                separator = QFrame()
                separator.setFrameShape(QFrame.Shape.HLine)
                separator.setStyleSheet("color: #e0e0e0;")
                layout.addWidget(separator)
        
        parent_layout.addWidget(group)
    
    def create_time_row(self, enabled=False, time_index=1):
        """创建时间段行"""
        row_layout = QHBoxLayout()
        row_layout.setSpacing(15)
        
        # 开关
        switch = ToggleSwitch("", enabled)
        self.ui_fields[f'time_switch_{time_index}'] = switch
        row_layout.addWidget(switch)
        
        # 开关标签
        switch_label = QLabel("启用")
        switch_label.setStyleSheet("color: black; font-size: 12px; min-width: 30px;")
        row_layout.addWidget(switch_label)
        
        # 时间选择器
        time_combos = []
        combo_keys = [f'hour_start_{time_index}', f'minute_start_{time_index}', f'hour_end_{time_index}', f'minute_end_{time_index}']
        
        for i in range(4):  # 4个时间选择器
            combo = QComboBox()
            combo.setFixedWidth(60)
            if i % 2 == 0:  # 小时
                combo.addItems([f"{h:02d}" for h in range(24)])
            else:  # 分钟
                combo.addItems([f"{m:02d}" for m in [0, 15, 30, 45]])
            combo.setStyleSheet("""
                QComboBox {
                    background-color: white;
                    color: black;
                    border: 1px solid #ccc;
                    padding: 4px;
                    border-radius: 3px;
                }
            """)
            self.ui_fields[combo_keys[i]] = combo
            time_combos.append(combo)
            row_layout.addWidget(combo)
            
            # 添加分隔符
            if i == 1:
                separator_label = QLabel("至")
                separator_label.setStyleSheet("color: black; font-weight: bold;")
                row_layout.addWidget(separator_label)
        
        # 设置默认时间
        if enabled:
            time_combos[0].setCurrentText("09")
            time_combos[1].setCurrentText("00")
            time_combos[2].setCurrentText("18")
            time_combos[3].setCurrentText("00")
        
        # 过滤今日已聊开关
        filter_switch = ToggleSwitch("", enabled)
        self.ui_fields[f'filter_switch_{time_index}'] = filter_switch
        row_layout.addWidget(filter_switch)
        
        filter_label = QLabel("过滤今日已聊")
        filter_label.setStyleSheet("color: black; font-size: 12px;")
        row_layout.addWidget(filter_label)
        
        row_layout.addStretch()
        
        return row_layout
    
    def create_message_text_rows(self, time_index=1):
        """创建消息文本框行"""
        main_layout = QVBoxLayout()
        main_layout.setSpacing(8)
        
        # 文本框内容
        text_boxes = [
            "社区全职高薪公司新设立的业务部门，主",
            "我们准备资源提供帮助吸收优秀的人才3-6K不", 
            "1.上班时间早九晚六，周末双休不加班"
        ]
        
        # 已读行
        read_row = QHBoxLayout()
        read_row.setSpacing(10)
        
        read_label = QLabel("已读")
        read_label.setStyleSheet("""
            QLabel {
                color: #27ae60;
                font-size: 12px;
                font-weight: bold;
                min-width: 35px;
                max-width: 35px;
            }
        """)
        read_row.addWidget(read_label)
        
        for i in range(3):
            text_edit = QLineEdit()  # 使用QLineEdit简化
            text_edit.setText(text_boxes[i])
            text_edit.setStyleSheet("""
                QLineEdit {
                    background-color: white;
                    color: black;
                    border: 1px solid #ccc;
                    padding: 6px;
                    border-radius: 3px;
                    font-size: 11px;
                }
            """)
            self.ui_fields[f'read_message_{time_index}_{i+1}'] = text_edit
            read_row.addWidget(text_edit)
        
        main_layout.addLayout(read_row)
        
        # 未读行
        unread_row = QHBoxLayout()
        unread_row.setSpacing(10)
        
        unread_label = QLabel("未读")
        unread_label.setStyleSheet("""
            QLabel {
                color: #e74c3c;
                font-size: 12px;
                font-weight: bold;
                min-width: 35px;
                max-width: 35px;
            }
        """)
        unread_row.addWidget(unread_label)
        
        for i in range(3):
            text_edit = QLineEdit()  # 使用QLineEdit简化
            text_edit.setText(text_boxes[i])
            text_edit.setStyleSheet("""
                QLineEdit {
                    background-color: white;
                    color: black;
                    border: 1px solid #ccc;
                    padding: 6px;
                    border-radius: 3px;
                    font-size: 11px;
                }
            """)
            self.ui_fields[f'unread_message_{time_index}_{i+1}'] = text_edit
            unread_row.addWidget(text_edit)
        
        main_layout.addLayout(unread_row)
        
        return main_layout
    
    def create_auto_reply_tab(self):
        """创建自动回复标签页"""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        
        # 自动回复设置
        settings_group = QGroupBox("⚙️ 自动回复设置")
        settings_layout = QVBoxLayout(settings_group)
        
        # 启用自动回复
        enable_layout = QHBoxLayout()
        enable_cb = QCheckBox("启用自动回复")
        enable_cb.setChecked(True)
        enable_layout.addWidget(enable_cb)
        enable_layout.addStretch()
        settings_layout.addLayout(enable_layout)
        
        # 回复延迟设置
        delay_layout = QHBoxLayout()
        delay_layout.addWidget(QLabel("回复延迟:"))
        
        delay_spin = QSpinBox()
        delay_spin.setRange(1, 300)
        delay_spin.setValue(10)
        delay_spin.setSuffix(" 秒")
        delay_layout.addWidget(delay_spin)
        
        delay_layout.addStretch()
        settings_layout.addLayout(delay_layout)
        
        # 智能回复
        smart_layout = QHBoxLayout()
        smart_cb = QCheckBox("启用智能回复")
        smart_layout.addWidget(smart_cb)
        smart_layout.addStretch()
        settings_layout.addLayout(smart_layout)
        
        layout.addWidget(settings_group)
        
        # 回复模板管理
        templates_group = QGroupBox("📝 回复模板")
        templates_layout = QVBoxLayout(templates_group)
        
        # 添加模板
        add_template_layout = QHBoxLayout()
        
        keyword_input = QLineEdit()
        keyword_input.setPlaceholderText("触发关键词")
        add_template_layout.addWidget(keyword_input)
        
        reply_input = QTextEdit()
        reply_input.setMaximumHeight(60)
        reply_input.setPlaceholderText("回复内容")
        add_template_layout.addWidget(reply_input)
        
        add_btn = QPushButton("添加")
        add_btn.setStyleSheet("""
            QPushButton {
                background-color: #27ae60;
                color: white;
                border: none;
                padding: 10px 20px;
                border-radius: 4px;
            }
        """)
        add_template_layout.addWidget(add_btn)
        
        templates_layout.addLayout(add_template_layout)
        
        # 模板列表
        templates_table = QTableWidget()
        templates_table.setColumnCount(3)
        templates_table.setHorizontalHeaderLabels(["关键词", "回复内容", "操作"])
        
        # 示例模板数据
        template_data = [
            ["你好", "你好！很高兴认识你"],
            ["谢谢", "不客气，有什么需要帮助的吗？"],
            ["再见", "再见！期待下次聊天"]
        ]
        
        templates_table.setRowCount(len(template_data))
        for row, data in enumerate(template_data):
            for col, value in enumerate(data):
                item = QTableWidgetItem(str(value))
                templates_table.setItem(row, col, item)
        
        templates_layout.addWidget(templates_table)
        layout.addWidget(templates_group)
        
        return widget
    
    def create_analysis_tab(self):
        """创建聊天分析标签页"""
        widget = QWidget()
        layout = QVBoxLayout(widget)
        
        # 统计概览
        stats_layout = QGridLayout()
        
        stats_data = [
            ("今日聊天", "25", "#3498db"),
            ("活跃用户", "18", "#27ae60"),
            ("回复率", "85%", "#f39c12"),
            ("平均响应", "2.5分钟", "#9b59b6")
        ]
        
        for i, (title, value, color) in enumerate(stats_data):
            stat_widget = QFrame()
            stat_widget.setStyleSheet(f"""
                QFrame {{
                    background-color: {color};
                    border-radius: 8px;
                    padding: 20px;
                }}
                QLabel {{
                    color: white;
                    font-weight: bold;
                }}
            """)
            
            stat_layout = QVBoxLayout(stat_widget)
            
            title_label = QLabel(title)
            title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
            stat_layout.addWidget(title_label)
            
            value_label = QLabel(value)
            value_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
            value_label.setStyleSheet("font-size: 24px;")
            stat_layout.addWidget(value_label)
            
            stats_layout.addWidget(stat_widget, 0, i)
        
        layout.addLayout(stats_layout)
        
        # 详细分析
        analysis_group = QGroupBox("📈 详细分析")
        analysis_layout = QVBoxLayout(analysis_group)
        
        # 这里可以添加图表组件
        analysis_text = QTextEdit()
        analysis_text.setReadOnly(True)
        analysis_text.setPlainText("""
聊天分析报告：

1. 今日聊天总数：25次
2. 最活跃时间段：14:00-16:00
3. 平均对话轮数：8.5轮
4. 用户满意度：92%
5. 常用关键词：你好(15次)、谢谢(12次)、再见(8次)

建议：
- 在活跃时间段增加人工客服
- 优化常用关键词的回复模板
- 提高响应速度以提升用户体验
        """)
        
        analysis_layout.addWidget(analysis_text)
        layout.addWidget(analysis_group)
        
        return widget